package com.etop.weiway.wxmanage.controller;

import com.etop.weiway.basic.controller.BaseController;
import com.etop.weiway.commons.annotation.AccountRequired;
import com.etop.weiway.commons.web.Pager;
import com.etop.weiway.wxmanage.entity.MaterialNews;
import com.etop.weiway.wxmanage.entity.WeixinUser;
import com.etop.weiway.wxmanage.service.MaterialService;
import com.etop.weiway.wxmanage.service.WxUserManageService;
import com.etop.weiway.wxmanage.service.WxUserMessageService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.Date;

/**
 * 用户消息管理及客服回复控制器
 * Created by Jeremie on 2015/1/15.
 */
@Controller
@RequestMapping("/wxmanager/message")
public class WxUserMessageController extends BaseController {
    @Autowired
    private WxUserMessageService wxUserMessageService;
    @Autowired
    private WxUserManageService wxUserManageService;
    @Autowired
    private MaterialService materialService;

    /**
     * 跳转到消息列表页面
     *
     * @param keyWord
     * @param session
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequiresPermissions("menu:message")
    @RequestMapping("/list")
    @AccountRequired
    public String toMsgListPage(String keyWord, HttpSession session,
                                HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setAttribute("search", keyWord);
        request.setAttribute("pager", wxUserMessageService.getWxMsgListByAccountId(new Pager<>(request, response),
                (Integer) session.getAttribute("currentAccoutId"), keyWord));
        return "/home/wxmanage/base/wxUserMessage/userMsgList";
    }

    /**
     * 根据媒体id和媒体类型来下载媒体文件
     *
     * @param mediaId
     * @param type
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/download")
    public void downMedia(String mediaId, String type, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String suffix = null;
        if ("voice".equals(type)) {
            suffix = ".mp3";
        }
        String path = request.getServletContext().getRealPath("/");
        if (!path.endsWith("/")) {
            path += "/";
        }
        path += "home/wxmanage/temp/" + mediaId + suffix;

        response.reset();
        response.addHeader("Content-Disposition", "attachment;filename=" + mediaId + suffix);
        response.addHeader("Content-Length", "" + new File(path).length());
        response.setContentType("application/octet-stream");

        FileInputStream in = null;
        OutputStream out = null;
        try {
            in = new FileInputStream(path);
            out = response.getOutputStream();
            byte[] b = new byte[1024];
            int len = -1;
            while ((len = in.read(b)) != -1) {
                out.write(b, 0, len);
            }
            out.flush();
        } catch (Exception ex) {
            throw ex;
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }

    /**
     * 删除消息记录
     *
     * @param id
     * @param target
     * @param source
     * @param redirectAttributes
     * @return
     * @throws Exception
     */
    @RequestMapping("/delete")
    public String deleteMsg(String id, String openId, String target, String source, RedirectAttributes redirectAttributes) throws Exception {
        if ("user".equals(target)) {
            wxUserMessageService.deleteUserMsgById(id);
        } else {
            wxUserMessageService.deleteCustomReplyById(id);
        }
        addMessage(redirectAttributes, SUCCESS, "删除成功!");
        if ("list".equals(source)) {
            return "redirect:/wxmanager/message/list";
        } else {
            redirectAttributes.addAttribute("openId", openId);
            return "redirect:/wxmanager/message/chat";
        }
    }

    /**
     * 跳转到聊天界面
     *
     * @param openId
     * @param session
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/chat")
    public String toChatPage(String openId, HttpSession session, HttpServletRequest request) throws Exception {
        Integer accountId = (Integer) session.getAttribute("currentAccoutId");
        WeixinUser user = wxUserManageService.findWxUser(accountId, openId);
        request.setAttribute("list", wxUserMessageService.getChatRecord(user, accountId));
        request.setAttribute("user", user);
        return "/home/wxmanage/base/wxUserMessage/chat";
    }

    /**
     * 发送消息给用户(快捷回复)
     *
     * @param openId
     * @param content
     * @param mid
     * @param materialType
     * @param materialId
     * @param session
     * @param request
     * @param redirectAttributes
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/post", method = RequestMethod.POST)
    public String postMsg(String openId, String content, String mid, String materialType, String materialId,
                          HttpSession session, HttpServletRequest request, RedirectAttributes redirectAttributes) throws Exception {
        boolean sendResult = false;
        String strFullUrl = request.getRequestURL().toString();
        int funcIndex = strFullUrl.indexOf("/wxmanager");
        String url = strFullUrl.replace(strFullUrl.substring(funcIndex), "");
        String path = request.getServletContext().getRealPath("/");
        if (!path.endsWith("/") && !path.endsWith("\\"))
            path += "/";
        switch (materialType) {
            case "text":
                sendResult = wxUserMessageService.saveAndPostTextMsg(openId, content, mid, (Integer) session.getAttribute("currentAccoutId"));
                break;
            case "image":
                sendResult = wxUserMessageService.saveAndPostImageMsg((Integer) session.getAttribute("currentAccoutId"), openId, materialId, path);
                break;
            case "voice":
                sendResult = wxUserMessageService.saveAndPostVoiceMsg((Integer) session.getAttribute("currentAccoutId"), openId, materialId, path);
                break;
            case "video":
                sendResult = wxUserMessageService.saveAndPostVideoMsg((Integer) session.getAttribute("currentAccoutId"), openId, materialId, path);
                break;
            case "news":
                sendResult = wxUserMessageService.saveAndPostNewsMsg((Integer) session.getAttribute("currentAccoutId"), openId, materialId, url);
                break;
            case "mutinews":
                sendResult = wxUserMessageService.saveAndPostMultinewsMsg((Integer) session.getAttribute("currentAccoutId"), openId, materialId, url);
                break;
            default:
                break;
        }
        addMessage(redirectAttributes, sendResult ? SUCCESS : ERROR, sendResult ? "回复成功!" : "回复失败!");
        if (mid != null && !"".equals(mid)) {
            return "redirect:/wxmanager/message/list";
        } else {
            redirectAttributes.addAttribute("openId", openId);
            return "redirect:/wxmanager/message/chat";
        }
    }

    /**
     * 异步返回新消息的数量
     *
     * @param time
     * @param openId
     * @param session
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/count", method = RequestMethod.POST)
    public String getNewMessageCount(String time, String openId, HttpSession session) throws Exception {
        Integer accountId = (Integer) session.getAttribute("currentAccoutId");
        if (accountId != null) {
            return wxUserMessageService.getNewMessageCount(time, openId, accountId).toString();
        } else {
            return "0";
        }
    }

    /**
     * 跳转到图文消息详情界面
     *
     * @param materialId
     * @param time
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/detail")
    @AccountRequired
    public String toNewsDetail(String materialId, String time, HttpServletRequest request) throws Exception {
        MaterialNews news = materialService.loadMaterialNews(Integer.parseInt(materialId));
        request.setAttribute("news", news);
        request.setAttribute("time", (time != null && !"".equals(time)) ? Long.parseLong(time) : new Date().getTime());
        return "/home/wxmanage/base/wxUserMessage/detail";
    }
}
